const { url } = require('../config/index.js')

/**
 * 小程序登录
 * 微信小程序授权流程：先传code过来；返回：STATUS_CODE = 2；OPEN_ID = openid
 * 再用getUserInfo获取用户信息；把OPEN_ID和ENCRYPTED_DATA和IV再传给后台；这次code一定不要传
 */
function commonLogin() {

  return new Promise(function (resolve, reject) {
    wx.showLoading()
    wx.login({
      success: res => {

        // 先传code过来；返回：STATUS_CODE = 2
        wx.request({
          url: url + 'User/appletAuthorization.action',
          method: 'POST',
          data: {
            CODE: res.code
          },
          success: res1 => {
            console.log(res1.data)
            if (res1.data.STATUS_CODE == 2) {
// -----------
              // 获取用户信息
              wx.getUserInfo({
                withCredentials: true,
                success: function (response) {
                  console.warn(response)
                  let userInfo = response.userInfo

                  // 后台返回授权信息
                  wx.request({
                    url: url + 'User/appletAuthorization.action',
                    method: 'POST',
                    data: {
                      OPEN_ID: res1.data.OPEN_ID,
                      IV: response.iv,
                      ENCRYPTED_DATA: response.encryptedData
                    },
                    success: res2 => {
                      console.warn('loginsuc')
                      console.log(res2.data)
                      if (res2.data.STATUS_CODE === 1) {
                        wx.hideLoading()
                        resolve(res2.data)
                        // 存授权信息
                        wx.setStorageSync('userInfo', res2.data)
                      } else {
                        reject(res2)
                      }
                    },
                    fail: err => {
                      console.warn('login fail')
                      // console.log(err)
                    }
                  })
                },
                fail: err => {
                  // 若用户拒绝授权，提示用户在设置中打开授权
                  console.error('用户拒绝授权')
                  reject(err)
                  wxShowAuth()
                }
              })
// -----------
            } else {
              reject(res)
            }
          },
          fail: err => {
            console.warn('loginerr')
            console.log(err)
          }
        })

      },
      fail: error => {
        reject(error)
      }
    })
  })

}
// 拒绝授权弹出
function wxShowAuth () {
  wx.showModal({
    title: '提示',
    content: '由于您拒绝授权，请在设置中重新打开授权',
    showCancel: false,
    success: function (res) {
      if (res.confirm) {
        // 调起客户端小程序设置界面，返回用户设置的操作结果。
        wx.openSetting({
          success: (res) => {
            let canUseUserInfo = res.authSetting['scope.userInfo']
            console.warn(canUseUserInfo)
            // 用户同意信息授权
            if (canUseUserInfo) {
              // 清楚拒绝授权标识
              wx.removeStorageSync('refuseAuth')
              commonLogin()
            } else {
              // 仍决绝授权，关闭
              // wx.navigateBack({
              //   delta: -1
              // })
              wxShowAuth()
            }

          }
        })
      } else if (res.cancel) {
        // wx.navigateBack({
        //   delta: -1
        // })
      }
    }
  })
}
/**
 * 定位
 */
function getLocation () {
  return new Promise(function (resolve, reject) {
    wx.getLocation({
      type: 'wgs84',
      success: res => {
        // console.log(res)
        wx.setStorageSync('location', res)
        resolve(res)
      },
      fail: err => {
        let location = {
          "latitude": 22.53332, 
          "longitude": 113.93041
        }
        // 拒绝定位，手动设置深圳
        wx.setStorageSync('location', location)
        console.log(err)
        reject(err)
      }
    })
  })
}
/**
 * 获取用户收货地址
 * uid 用户id
 */
function getUserAddress (uid) {

  return new Promise(function (resolve, reject) {

        wx.request({
          url: url + 'UserAdr/getUserAdrList.action',
          method: 'POST',
          data: {
            USER_ID: uid
          },
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
          success: res => {
            // console.log(res.data)
            if (res.data.STATUS_CODE === 1) {
              resolve(res.data.RESULT_DATA)
            } else {
              reject(res)
            }
          }
        })

    })

}
/**
 * 跳转网页
 * url：地址
 * title：为当前webview设置的title
 */
function jumpWebView(url, title) {
  wx.setStorageSync('jumpUrl', {
    url: url,
    title: title
  })
  wx.navigateTo({
    url: '/pages/webView/webView',
  })
}
/**
 * 用户是否有设置支付密码
 * uid 用户id
 */
function hasPassword(uid) {

  return new Promise(function (resolve, reject) {

    wx.request({
      url: url + '/pospal/verifyPospalUserPasswordIsNull.action',
      method: 'POST',
      data: {
        USER_ID: uid
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: res => {
        if (res.data.STATUS_CODE === 1) {
          resolve(res.data)
        } else {
          reject(res.data)
        }
      }
    })

  })

}
// 请求会员等级提醒接口，获取用户在本次支付后是否升级
function commonSuccess() {
  
  wx.request({
    url: url + 'PointCash/getUpgradeRemind.action',
    method: 'POST',
    header: {
      'content-type': 'application/x-www-form-urlencoded'
    },
    data: {
      USER_ID: wx.getStorageSync('userInfo').USER_ID
    },
    success: res => {
      // console.log(res.data)
      if (res.data.STATUS_CODE == 1) {
        if (res.data.REMIND == 0) { // 0 需提示用户已升级
          wx.redirectTo({ // 跳转升级提示
            url: '/pages/commonSuccessPage/commonSuccessPage?type=levelup&level=' + res.data.GRADE
          })
        } else {
          wx.redirectTo({ // 跳转支付成功
            url: '/pages/commonSuccessPage/commonSuccessPage?type=paysuccess'
          })
        }
      } else {
        wx.redirectTo({ // 跳转支付成功
          url: '/pages/commonSuccessPage/commonSuccessPage?type=paysuccess'
        })
      }
    },
    fail: res => {
      wx.redirectTo({ // 跳转支付成功
        url: '/pages/commonSuccessPage/commonSuccessPage?type=paysuccess'
      })
    }
  })

}
function getUserPhone () {
  return new Promise(function (resolve, reject) {

    wx.request({
      url: url + 'User/getCarUserInfo.action',
      method: 'POST',
      data: {
        USER_ID: wx.getStorageSync('userInfo').USER_ID
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: res => {
        if (res.data.STATUS_CODE === 1) {
          resolve(res.data)
        } else {
          reject(res.data)
        }
      }
    })

  })
}

module.exports = {
  commonLogin,
  getLocation,
  getUserAddress,
  jumpWebView,
  hasPassword,
  commonSuccess,
  getUserPhone
}
